import glob
from pathlib import Path

from pikepdf import Pdf


# pip install pikepdf
# see https://pikepdf.readthedocs.io/en/latest/installation.html

def remove_bookmarks(pdf_file, output_file):
    example = Pdf.open(pdf_file, allow_overwriting_input=True)
    example.Root.Outlines = {}
    example.save(output_file)
    if output_file == pdf_file:
        print(pdf_file)
    else:
        print(f'{pdf_file}-->{output_file}')


def all_pdfs_remove_bookmarks(pdfs_dir, outputs_dir=None):
    for pdf_file in glob.glob(rf"{pdfs_dir}\*.pdf", recursive=True):
        if outputs_dir:
            output_file = pdf_file.replace(pdfs_dir, outputs_dir)
            # print(to_docx_file)
            if Path(output_file).exists():
                continue
        else:
            output_file = pdf_file
        remove_bookmarks(pdf_file, output_file)


if __name__ == '__main__':
    # 原地替换
    all_pdfs_remove_bookmarks(r"C:\Users\yang.lei\Downloads\pdfs")
    # 输出到其他文件夹
    # all_pdfs_remove_bookmarks(r"C:\Users\yang.lei\Downloads\pdfs", r"C:\Users\yang.lei\Downloads\rmbookmarks")
